import { navigateTo, redirectTo, showToast } from "utils/index";
App({
  globalData: {
    env: "dev", //当前环境，可选值：dev, test, prod
    userInfo: null, //有数据则说明已登录，否则未登录
    hasNetwork: true,
    isPlaying: false, //是否处于播放中
    currSongId: "", //当前歌曲的id
  },
  onLaunch() {
    this.initSystemInfo(this);
    this.watchNetworkStatus();
    this.watchMiniAppUpdate();
    this.login();
    this.init();
  },
  async onShow() {
    const hasNet = await this.checkNetworkStatus();
    this.globalData.hasNetwork = hasNet;
  },
  //初始化数据
  init() {
    //当前环境  develop(开发)、trial(体验)、release(正式)
    const env = wx.getAccountInfoSync().miniProgram.envVersion;
    const envMap = {
      release: "prod",
      trial: "test",
      develop: "dev",
    };
    this.globalData.env = envMap[env];
    //     this.watchMiniAppUpdate();
    //     this.login();
    //     // this.getWxUserInfo();
    //     // const hasLogin = true;
    //     // if (!hasLogin) {
    //     //   //如果有必要，可以添加白名单
    //     //   const path = "";
    //     //   if (!noAuthPageList.includes(path)) {
    //     //     navigateTo("/pages/login/login");
    //     //   }
    //     // }
  },
  //初始化系统信息
  initSystemInfo(app) {
    wx.getSystemInfo({
      success(sysInfo) {
        const menuButton = wx.getMenuButtonBoundingClientRect();
        const { statusBarHeight, windowWidth } = sysInfo;
        const { top, height, width, right } = menuButton;
        const navBarHeight =
          (top - statusBarHeight) * 2 + height + statusBarHeight;
        app.globalData.systemInfo = { ...sysInfo, menuButton, navBarHeight };
      },
    });
  },
  //检查网络状态
  async checkNetworkStatus() {
    return await wx
      .getNetworkType()
      .then((res) => {
        let { networkType } = res;
        if (["2g", "3g"].includes(networkType)) {
          showToast("当前网络较慢");
        } else if (networkType === "none") {
          showToast("无网络，请检查网络连接");
          return false;
        }
        // wx.hideLoading();
        return true;
      })
      .catch((err) => {
        console.log("getNetworkType error:", err);
        return false;
      });
  },
  //监听网络状态的改变， 比如 4g切换wifi wifi切换成3g
  watchNetworkStatus() {
    wx.onNetworkStatusChange((res) => {
      let { isConnected, networkType } = res;
      this.globalData.hasNetwork = isConnected;
      if (!isConnected) {
        // showToast("无网络，请检查网络连接");
        // wx.hideLoading();
        const pages = getCurrentPages();
        const currRoute = pages.length ? pages.slice(-1)[0].route : "";
        if (currRoute !== "pages/no-network/no-network") {
          navigateTo("/pages/no-network/no-network");
        }
      }
      if (["2g", "3g"].includes(networkType)) {
        showToast("当前网络较慢");
      }
    });
  },
  //监听小程序更新
  watchMiniAppUpdate() {
    const updateManager = wx.getUpdateManager();
    if (!updateManager) return;
    updateManager.onCheckForUpdate((res) => {
      let hasNewVersion = res.hasUpdate;
      if (hasNewVersion) {
        updateManager.onUpdateReady(() => {
          wx.showModal({
            title: "新版本已经准备好，请重启应用",
            confirmColor: "#00BE8C",
            showCancel: false,
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate();
              }
            },
          });
        });
        updateManager.onUpdateFailed(() => {
          showToast("新版本下载失败！", "error");
        });
      }
    });
  },
  //登录
  login() {
    const that = this;
    wx.login({
      success(res) {
        let { code } = res;
        const token = wx.getStorageSync("token");
        // console.log("微信登录成功！", res);
        // GetUserInfo({
        //   timestamp: 1654068363,
        //   token: "8b6da2909486d5d0889ef58f08d2f75a",
        //   appname: "wechat",
        //   appid: appId.main,
        //   code: code,
        // }).then((res) => {
        // console.log("res--res--res", res);
        const userInfo = wx.getStorageSync("userInfo");
        that.globalData.userInfo = userInfo;
        // });
        // http(
        //   "get",
        //   "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code",
        //   {
        //     appid: "wxb02a5b5ceb60d3a4",
        //     secret: "2c548de42f6cb3a1229221cdbc227da8",
        //     js_code: code,
        //     grant_type: "authorization_code",
        //   }
        // ).then((res) => {
        //   let { session_key, openid } = res;
        //   console.log(`session_key: ${session_key}       openid: ${openid}`);
        // });
      },
      fail(err) {
        console.error("微信登录失败：" + err);
      },
    });
  },
  //获取微信的用户信息
  getWxUserInfo() {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting && res.authSetting["scope.userInfo"]) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (data) {
              console.log(data.userInfo, "微信用户信息————user-info");
              // {
              //   avatarUrl: '微信头像img文件path'
              //   nickname: '微信昵称'
              // }
            },
          });
        } else {
          this.showShouquan = true; // 打开模态框进行授权
        }
      },
    });
  },
});
